package com.demo.intercepter;

import com.demo.custom.PrometheusMetricsCustom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器，用来统计访问次数
 */

@Component
public class PrometheusMetricsGaugeInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    PrometheusMetricsCustom prometheusMetricsCustom;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        int status = response.getStatus();
        //请求数量
        prometheusMetricsCustom.getRequestMax().labels(requestURI, method, String.valueOf(status)).inc();
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        int status = response.getStatus();
        super.afterCompletion(request, response, handler, ex);
    }
}
